<?php 
	require_once '../function.php';

	$user = xiu_get_current_user_admin();

	// 获取所有用户信息
	// ============================================================
	$users = xiu_fetch_db_all('select * from users where id >1;');

	// 获取编辑用户的信息
	if (!empty($_GET['id'])) {
		$id = $_GET['id'];	
		$modify_user = xiu_fetch_db_one('select * from users where id='.$id.';');
	}


	// 添加用户
	// ============================================================
	function add_user(){

		if ($_FILES['avatar']['size'] === 0) {
			$GLOBALS['message'] = '请选择图片';
			return;
		}

		if (empty($_POST['nickname'])) {
			$GLOBALS['message'] = '请输入昵称';
			return;
		}

		if (empty($_POST['slug'])) {
			$GLOBALS['message'] = '请输入别名';
			return;
		}

		if (empty($_POST['username'])) {
			$GLOBALS['message'] = '请输入用户名';
			return;
		}

		if (empty($_POST['password'])) {
			$GLOBALS['message'] = '请输入密码';
			return;
		}
		if (!isset($_POST['status'])) {
			echo $_POST['status'];
			$GLOBALS['message'] = '请选择状态';
			return;
		}

		$nickname = $_POST['nickname'];
		$slug = $_POST['slug'];
		$username = $_POST['username'];
		$password = $_POST['password'];
		$status = $_POST['status'];
		$avatar = $_FILES['avatar'];



		// 图片接收
		// ================================================
		// array(5) {
		//   ["name"]=>
		//   string(10) "avatar.jpg"
		//   ["type"]=>
		//   string(10) "image/jpeg"
		//   ["tmp_name"]=>
		//   string(27) "C:\Windows\Temp\php77DF.tmp"
		//   ["error"]=>
		//   int(0)
		//   ["size"]=>
		//   int(25656)
		// }


		$suffix_arr = array('jpg', 'jpeg', 'png');
		$suffix = explode('.', $avatar['name'])[1];
		if (!in_array($suffix, $suffix_arr)) {
			$GLOBALS['message'] = '仅支持上传jpg、jpeg、png格式的图片';
			return;
		}

		// 验证图片的MIMETYPE
		$mimetype_array = array('image/jpg', 'image/jpeg', 'image/png');
		if (!in_array($avatar['type'], $mimetype_array)) {
			$GLOBALS['message'] = '仅支持jpg,jpeg,png格式的图片';
			return;
		}

		if ($avatar['error'] !== UPLOAD_ERR_OK) {
			$GLOBALS['message'] = '头像上传失败';
			return;
		}

		$file_name = $avatar['tmp_name'];
		$target = '../static/uploads/avatar/'.uniqid().'.'.$suffix;

		$moved = move_uploaded_file($file_name, $target);
		if (!$moved) {
			$GLOBALS['message'] = '上传头像失败';
			return;
		}

		$affect_rows = xiu_operation_db("insert into users values(null, '{$slug}', '{$username}', '{$password}', '{$nickname}', '{$target}', null, {$status})");

		if ($affect_rows <= 0) {
			$GLOBALS['message'] = '添加用户失败';
			return;
		}

		header('Location: /admin/users.php');
	}

	function modify_user(){
		global $modify_user;
		$nickname = empty($_POST['nickname']) ? $modify_user['nickname'] : $_POST['nickname'];
		$slug = empty($_POST['slug']) ? $modify_user['slug'] : $_POST['slug'];
		$username = empty($_POST['username']) ? $modify_user['username'] : $_POST['username'];
		$password = empty($_POST['password']) ? $modify_user['password'] : $_POST['password'];
		$status = $_POST['status'];
		if ($_FILES['avatar']['size'] == 0) {
			$target = $modify_user['avatar'];
		}else{
			$avatar = $_FILES['avatar'];

			$suffix_arr = array('jpg', 'jpeg', 'png');
			// 获取文件后缀名
			$file_suffix = explode('.', $avatar['name'])[1];
			if (!in_array($file_suffix, $suffix_arr)) {
				$GLOBALS['message'] = '仅支持jpg,jpeg,png格式的图片';
				return;
			}
			// 验证图片的MIMETYPE
			$mimetype_array = array('image/jpg', 'image/jpeg', 'image/png');
			if (!in_array($avatar['type'], $mimetype_array)) {
				$GLOBALS['message'] = '仅支持jpg,jpeg,png格式的图片';
				return;
			}

			if ($avatar['error'] !== UPLOAD_ERR_OK) {
				$GLOBALS['message'] = "上传失败！";
				return;
			}
			
			$file_name = $avatar['tmp_name'];
			$target = '../static/uploads/avatar/'.uniqid().$avatar['name'];

			//将文件从临时文件夹移动至网站目录
			$moved = move_uploaded_file($file_name, $target);
			if (!$moved) {
				$GLOBALS['message'] = '文件上传失败！';
				return;
			}
		}

		// 文件上传成功
		$affect_rows = xiu_operation_db("update users set id={$modify_user['id']},slug='{$slug}',username='{$username}',password='{$password}',nickname='{$nickname}',avatar='{$target}',status='{$status}' where id = {$modify_user['id']};");


		if ($affect_rows < 0) {
			$GLOBALS['message'] = '修改用户信息失败';
			return;
		}

		header('Location: /admin/users.php');
	}

	if ($_SERVER['REQUEST_METHOD'] === 'POST') {
		if (empty($_GET['id'])) {
			add_user();
		}else{
			modify_user();
		}
	}

 ?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>用户</title>
	<link rel="stylesheet" type="text/css" href="/static/vendors/bootstrap4.6/css/bootstrap.css">
	<link rel="stylesheet" type="text/css" href="/static/css/admin.css">
</head>
<body>
	<div class="main">
		<?php include './inc/navbar.php' ?>
		<div class="container-fluid">
			<div class="page-title">
				<h1>用户</h1>
			</div>

			<div class="row">
				<div class="col-md-4">
					<form action="<?php echo $_SERVER['PHP_SELF'] ?>?id=<?php echo isset($modify_user)?$modify_user['id'] : ''; ?>" method="post" enctype="multipart/form-data">
						<?php if (isset($message)): ?>
							<div class="alert alert-danger" role="alert">
								<?php echo $message; ?>
							</div>
						<?php endif ?>
						<div class="form-group">
					    	<label for="avatar">头像</label>
					    	<input type="file" name="avatar" id="avatar" class="form-control">
					  	</div>
					  	<div class="form-group">
					    	<label for="nickname">昵称</label>
					    	<input type="text" class="form-control" id="nickname" name="nickname" autocomplete="off" value="<?php echo isset($modify_user) ? $modify_user['nickname'] : ''; ?>">
					  	</div>
					  	<div class="form-group">
					    	<label for="slug">别名</label>
					    	<input type="text" class="form-control" id="slug" name="slug" autocomplete="off" value="<?php echo isset($modify_user) ? $modify_user['slug'] : ''; ?>">
					  	</div>
					  	<div class="form-group">
					    	<label for="username">用户名</label>
					    	<input type="text" class="form-control" id="username" name="username" autocomplete="off" value="<?php echo isset($modify_user) ? $modify_user['username'] : ''; ?>">
					  	</div>
					  	<div class="form-group">
					    	<label for="password">密码</label>
					    	<input type="password" class="form-control" id="password" name="password" autocomplete="off" value="<?php echo isset($modify_user) ? $modify_user['password'] : ''; ?>">
					  	</div>
					  	<div class="form-group">
					    	<label for="status">状态</label>
					    	<select name="status" class="form-control input-sm">
					    		<option value="0" <?php echo isset($modify_user)? ($modify_user['status'] == 0?'selected': '') : '' ?>>禁用</option>
					    		<option value="1" <?php echo isset($modify_user)? ($modify_user['status'] == 1?'selected': '') : '' ?>>正常</option>
					    	</select>
					  	</div>
					  	<div class="form-group">
							<button class="btn btn-primary" class="form-control" type="submit"><?php echo isset($_GET['id']) ? '保存' : '添加'; ?></button>
						</div>
					</form>
				</div>	
				<div class="col-md-8">
					<a id='categories_delete' class="btn btn-danger btn-sm" href="" style="display: none;">批量删除</a>
					<table class="table table-bordered table-hover">
						<thead>
							<tr>
								<th><input type="checkbox"></th>
								<th>id</th>
								<th>头像</th>
								<th>昵称</th>
								<th>别名</th>
								<th>用户名</th>
								<th>状态</th>
								<th>操作</th>
							</tr>
						</thead>
						<tbody>
							<?php foreach ($users as $key => $item): ?>
								<tr>
									<td><input type="checkbox"></td>
									<td><?php echo  $key + 1; ?></td>
									<td><img src="<?php echo $item['avatar']; ?>" width="50px"></td>
									<td><?php echo $item['nickname']; ?></td>
									<td><?php echo $item['slug']; ?></td>
									<td><?php echo $item['username']; ?></td>
									<td><?php echo $item['status'] == 1? '正常' : '禁用'; ?></td>
									<td>
										<a href="/admin/users.php?id=<?php echo $item['id']; ?>" class="btn btn-primary btn-sm">编辑</a>
										<a href="/admin/delete-user.php?id=<?php echo $item['id']; ?>" class="btn btn-danger btn-sm">删除</a>
									</td>
								</tr>
							<?php endforeach ?>
						</tbody>
					</table>
				</div>
			</div>
		</div>
	</div>

	<?php $current_page = 'users' ?>
	<?php include './inc/asid.php' ?>
	<script src="/static/vendors/jQuery.js"></script>
	<script src="/static/vendors/bootstrap4.6/js/bootstrap.js"></script>
</body>
</html>